﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using CommonClasses;


namespace PositionService 
{
    public partial class Service : ServiceBase 
    {
        private bool _started;

        public Service() {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _started = true;
            while (_started)
            {
                Thread.Sleep(1000 * 60);

                Order order = null;
                try
                {
                    order = DataProvider.Instance.GetNotProcessedOrders();
                    if (order == null) continue;
                    DataProvider.Instance.UpdateStatus(StatusOrder.InProcess, order.ID);

                    PositionChecker.Instance._orderToCheck = order;
                    PositionChecker.Instance._countEvent = new CountdownEvent(order.Adverts.Count);
                    foreach (Advert advert in order.Adverts)
                    {
                        new Thread(PositionChecker.Instance.CheckForOrder).Start(advert);
                    }
                    PositionChecker.Instance._countEvent.Wait();
                    DataProvider.Instance.UpdateStatus(StatusOrder.Complete, order.ID);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    if(order!=null)
                    {
                        DataProvider.Instance.UpdateStatus(StatusOrder.Error, order.ID);
                    }
                }
            }
        }

        protected override void OnStop()
        {
            _started = false;
        }
    }
}
